'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { TOPICS_INDEX } from '@/data/topics-index';

// 动态导入题库
const QUESTION_BANK: Record<string, any[]> = {};
import { CheckCircle, XCircle, AlertTriangle, ArrowRight, ArrowLeft } from 'lucide-react';

interface VerificationResult {
  topicId: string;
  topicName: string;
  questionIndex: number;
  issues: string[];
  severity: 'error' | 'warning' | 'info';
}

export default function VerifyQuestionsPage() {
  const [currentTopicIndex, setCurrentTopicIndex] = useState(0);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [results, setResults] = useState<VerificationResult[]>([]);
  const [showSolution, setShowSolution] = useState(false);

  const topics = TOPICS_INDEX;
  const currentTopic = topics[currentTopicIndex];
  const questions = QUESTION_BANK[currentTopic.id] || [];
  const currentQuestion = questions[currentQuestionIndex];

  const totalTopics = topics.length;
  const totalQuestions = questions.length;

  // 检查题目完整性
  function checkQuestion(question: any, topicId: string, index: number) {
    const issues: string[] = [];
    let severity: 'error' | 'warning' | 'info' = 'info';

    // 检查必需字段
    if (!question.stem || question.stem.trim() === '') {
      issues.push('❌ 题干为空');
      severity = 'error';
    }

    if (!question.answer || question.answer.length === 0) {
      issues.push('❌ 答案为空');
      severity = 'error';
    }

    if (!question.solution || question.solution.trim() === '') {
      issues.push('❌ 解析为空');
      severity = 'error';
    }

    // 检查题干长度
    if (question.stem && question.stem.length < 10) {
      issues.push('⚠️ 题干过短');
      if (severity === 'info') severity = 'warning';
    }

    // 检查解析长度
    if (question.solution && question.solution.length < 20) {
      issues.push('⚠️ 解析过短');
      if (severity === 'info') severity = 'warning';
    }

    // 检查难度
    if (!question.difficulty || question.difficulty < 1 || question.difficulty > 5) {
      issues.push('⚠️ 难度值无效');
      if (severity === 'info') severity = 'warning';
    }

    if (issues.length > 0) {
      return {
        topicId,
        topicName: currentTopic.name,
        questionIndex: index,
        issues,
        severity,
      };
    }

    return null;
  }

  // 标记问题
  function markIssue(type: 'error' | 'warning') {
    const issue = checkQuestion(currentQuestion, currentTopic.id, currentQuestionIndex);
    if (issue) {
      setResults([...results, issue]);
    } else {
      // 手动标记
      setResults([...results, {
        topicId: currentTopic.id,
        topicName: currentTopic.name,
        questionIndex: currentQuestionIndex,
        issues: [type === 'error' ? '❌ 手动标记为错误' : '⚠️ 手动标记为警告'],
        severity: type,
      }]);
    }
    nextQuestion();
  }

  // 下一题
  function nextQuestion() {
    if (currentQuestionIndex < totalQuestions - 1) {
      setCurrentQuestionIndex(currentQuestionIndex + 1);
      setShowSolution(false);
    } else if (currentTopicIndex < totalTopics - 1) {
      setCurrentTopicIndex(currentTopicIndex + 1);
      setCurrentQuestionIndex(0);
      setShowSolution(false);
    }
  }

  // 上一题
  function prevQuestion() {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(currentQuestionIndex - 1);
      setShowSolution(false);
    } else if (currentTopicIndex > 0) {
      setCurrentTopicIndex(currentTopicIndex - 1);
      const prevQuestions = QUESTION_BANK[topics[currentTopicIndex - 1].id] || [];
      setCurrentQuestionIndex(prevQuestions.length - 1);
      setShowSolution(false);
    }
  }

  // 跳转到题型
  function jumpToTopic(index: number) {
    setCurrentTopicIndex(index);
    setCurrentQuestionIndex(0);
    setShowSolution(false);
  }

  // 导出结果
  function exportResults() {
    const data = JSON.stringify(results, null, 2);
    const blob = new Blob([data], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `verification-results-${new Date().toISOString().split('T')[0]}.json`;
    a.click();
  }

  const progress = ((currentTopicIndex * 50 + currentQuestionIndex + 1) / (totalTopics * 50)) * 100;
  const errorCount = results.filter(r => r.severity === 'error').length;
  const warningCount = results.filter(r => r.severity === 'warning').length;

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 p-6">
      <div className="max-w-7xl mx-auto">
        {/* 标题 */}
        <div className="mb-6">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">题库质量检查工具</h1>
          <p className="text-gray-600">手工验证题目的准确性和完整性</p>
        </div>

        {/* 进度统计 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <div className="glassmorphism p-4 rounded-xl">
            <div className="text-2xl font-bold text-blue-600">{progress.toFixed(1)}%</div>
            <div className="text-sm text-gray-600">总体进度</div>
          </div>
          <div className="glassmorphism p-4 rounded-xl">
            <div className="text-2xl font-bold text-green-600">
              {currentTopicIndex * 50 + currentQuestionIndex + 1}
            </div>
            <div className="text-sm text-gray-600">已检查题目</div>
          </div>
          <div className="glassmorphism p-4 rounded-xl">
            <div className="text-2xl font-bold text-red-600">{errorCount}</div>
            <div className="text-sm text-gray-600">发现错误</div>
          </div>
          <div className="glassmorphism p-4 rounded-xl">
            <div className="text-2xl font-bold text-yellow-600">{warningCount}</div>
            <div className="text-sm text-gray-600">发现警告</div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* 题型列表 */}
          <div className="lg:col-span-1">
            <div className="glassmorphism p-4 rounded-xl max-h-[600px] overflow-y-auto">
              <h2 className="text-lg font-bold text-gray-800 mb-4">题型列表</h2>
              <div className="space-y-2">
                {topics.map((topic, index) => (
                  <button
                    key={topic.id}
                    onClick={() => jumpToTopic(index)}
                    className={`w-full text-left p-3 rounded-lg transition-all ${
                      index === currentTopicIndex
                        ? 'bg-indigo-100 border-2 border-indigo-500'
                        : 'bg-white/50 hover:bg-white/80'
                    }`}
                  >
                    <div className="font-medium text-gray-800">{topic.name}</div>
                    <div className="text-xs text-gray-500">
                      {QUESTION_BANK[topic.id]?.length || 0} 题
                    </div>
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* 题目显示 */}
          <div className="lg:col-span-2">
            <div className="glassmorphism p-6 rounded-xl mb-4">
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h2 className="text-xl font-bold text-gray-800">{currentTopic.name}</h2>
                  <p className="text-sm text-gray-600">
                    第 {currentQuestionIndex + 1} / {totalQuestions} 题
                  </p>
                </div>
                <div className="flex items-center space-x-2">
                  <span className={`px-3 py-1 rounded-full text-sm font-medium ${
                    currentQuestion?.difficulty === 1 ? 'bg-green-100 text-green-800' :
                    currentQuestion?.difficulty === 2 ? 'bg-blue-100 text-blue-800' :
                    currentQuestion?.difficulty === 3 ? 'bg-yellow-100 text-yellow-800' :
                    currentQuestion?.difficulty === 4 ? 'bg-orange-100 text-orange-800' :
                    'bg-red-100 text-red-800'
                  }`}>
                    难度 {currentQuestion?.difficulty}
                  </span>
                </div>
              </div>

              {/* 题干 */}
              <div className="mb-6">
                <h3 className="font-medium text-gray-700 mb-2">题目：</h3>
                <p className="text-gray-800 text-lg leading-relaxed whitespace-pre-line">
                  {currentQuestion?.stem}
                </p>
              </div>

              {/* 答案 */}
              <div className="mb-6">
                <h3 className="font-medium text-gray-700 mb-2">答案：</h3>
                <div className="bg-green-50 p-4 rounded-lg">
                  <p className="text-green-800 font-medium">
                    {currentQuestion?.answer?.join(' 或 ')}
                  </p>
                </div>
              </div>

              {/* 解析 */}
              <div className="mb-6">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="font-medium text-gray-700">解析：</h3>
                  <button
                    onClick={() => setShowSolution(!showSolution)}
                    className="text-sm text-indigo-600 hover:text-indigo-700"
                  >
                    {showSolution ? '隐藏' : '显示'}
                  </button>
                </div>
                {showSolution && (
                  <div className="bg-blue-50 p-4 rounded-lg">
                    <p className="text-gray-700 whitespace-pre-line">
                      {currentQuestion?.solution}
                    </p>
                  </div>
                )}
              </div>

              {/* 操作按钮 */}
              <div className="flex items-center justify-between">
                <button
                  onClick={prevQuestion}
                  disabled={currentTopicIndex === 0 && currentQuestionIndex === 0}
                  className="flex items-center px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <ArrowLeft className="w-4 h-4 mr-2" />
                  上一题
                </button>

                <div className="flex space-x-2">
                  <button
                    onClick={() => markIssue('error')}
                    className="flex items-center px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
                  >
                    <XCircle className="w-4 h-4 mr-2" />
                    标记错误
                  </button>
                  <button
                    onClick={() => markIssue('warning')}
                    className="flex items-center px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600"
                  >
                    <AlertTriangle className="w-4 h-4 mr-2" />
                    标记警告
                  </button>
                  <button
                    onClick={nextQuestion}
                    className="flex items-center px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600"
                  >
                    <CheckCircle className="w-4 h-4 mr-2" />
                    正确，下一题
                  </button>
                </div>

                <button
                  onClick={nextQuestion}
                  className="flex items-center px-4 py-2 bg-indigo-500 text-white rounded-lg hover:bg-indigo-600"
                >
                  下一题
                  <ArrowRight className="w-4 h-4 ml-2" />
                </button>
              </div>
            </div>

            {/* 问题列表 */}
            {results.length > 0 && (
              <div className="glassmorphism p-6 rounded-xl">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-bold text-gray-800">发现的问题</h3>
                  <button
                    onClick={exportResults}
                    className="px-4 py-2 bg-indigo-500 text-white rounded-lg hover:bg-indigo-600 text-sm"
                  >
                    导出结果
                  </button>
                </div>
                <div className="space-y-2 max-h-[300px] overflow-y-auto">
                  {results.map((result, index) => (
                    <div
                      key={index}
                      className={`p-3 rounded-lg ${
                        result.severity === 'error' ? 'bg-red-50 border-l-4 border-red-500' :
                        result.severity === 'warning' ? 'bg-yellow-50 border-l-4 border-yellow-500' :
                        'bg-blue-50 border-l-4 border-blue-500'
                      }`}
                    >
                      <div className="font-medium text-gray-800">
                        {result.topicName} - 第{result.questionIndex + 1}题
                      </div>
                      <div className="text-sm text-gray-600">
                        {result.issues.join(', ')}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

